const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const cors = require('cors')
app.listen(3000, () => {
  console.log('服务器已开启')
});

//post接参
app.use(express.urlencoded({
  extended: false
}));
app.use(express.json())

// 引入 db
const myquery = require('../js/db')

//配置cors
app.use(cors())
//资源静态化
app.use(express.static(__dirname));

//注册
app.post('/register',async (req, res, next) => {
  let {
    username,
    password,
    password2,
  } = req.body;
  if (!username || !password || !password2) {
    next("用户名或密码不能为空")
    return
  }
  if (password != password2) {
    next("两次密码不一致")
    return
  }
  // 运行sql语句，判断用户名是否存在
  let sql = `select * from member where username = '${username}'`;
  let [err, result] = await myquery(sql);
  if (err) {
    next(err);
    return;
  }
  // 已存在
  if (result.length > 0) {
    next('用户名已存在');
    return;
  }

  // 不存在就添加用户信息到表中
  let sql1 = `insert into member (username,password) values ('${username}','${password}')`;

  let [err1, result1] = await myquery(sql1);

  if (err1) {
    next(err1);
    return;
  }

  if (result1.insertId > 0) {
    res.send({
      code: 200,
      msg: '注册成功'
    })
  } else {
    next('请稍后再试')
  }

})

app.use((err, req, res, next) => {
  res.send({
    code: 400,
    msg: err
  })
})